package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.dto.OpportunityStageAddDTO;
import com.xbongbong.paas.pojo.dto.StageDefaultAndLinkOptionSaveDTO;
import com.xbongbong.paas.pojo.dto.StageProcessAddDTO;
import com.xbongbong.paas.pojo.dto.StageProcessArchiveDTO;
import com.xbongbong.paas.pojo.dto.StageProcessDeleteDTO;
import com.xbongbong.paas.pojo.dto.StageProcessEnableDTO;
import com.xbongbong.paas.pojo.dto.StageProcessGetDTO;
import com.xbongbong.paas.pojo.dto.StageProcessGetExceptDTO;
import com.xbongbong.paas.pojo.dto.StageProcessSaveDTO;
import com.xbongbong.paas.pojo.dto.StageProcessSortDTO;
import com.xbongbong.paas.pojo.dto.StageProcessVersionDTO;
import com.xbongbong.paas.pojo.dto.StageRatioAttrNameGetDTO;
import com.xbongbong.paas.pojo.dto.StageRatioAttrNameSetDTO;
import com.xbongbong.paas.pojo.vo.StageProcessArchiveVO;
import com.xbongbong.paas.pojo.vo.StageProcessEnableVO;
import com.xbongbong.paas.pojo.vo.StageProcessGetExceptVO;
import com.xbongbong.paas.pojo.vo.StageProcessGetVO;
import com.xbongbong.paas.pojo.vo.StageProcessVersionVO;
import com.xbongbong.paas.pojo.vo.StageRatioAttrNameGetVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.service.stage.StageProcessService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 阶段流程
 * @author 李少杰
 * @version v1.0.0
 * @date 2021/11/18 10:35
 */
@SuppressWarnings("deprecation")
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/stage/process")
public class StageProcessController {
    @Resource
    private StageProcessService stageProcessService;
    @Resource
    private PaasRedisHelper paasRedisHelper;


    /**
     * 流程版本
     * @param stageProcessVersionDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/version", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String processVersion(@RequestBody @Valid StageProcessVersionDTO stageProcessVersionDTO, BindingResult br) {
        XbbResponse<StageProcessVersionVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessVersionVO stageProcessVersionVO = stageProcessService.stageProcessVersion(stageProcessVersionDTO);
                response = new XbbResponse<>(stageProcessVersionVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 获取阶段流程
     * @param stageProcessGetDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String get(@RequestBody @Valid StageProcessGetDTO stageProcessGetDTO, BindingResult br) {
        XbbResponse<StageProcessGetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessGetVO stageProcessGetVO = stageProcessService.get(stageProcessGetDTO);
                response = new XbbResponse<>(stageProcessGetVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 阶段筛选（级联筛选：版本 + 阶段，默认为当前版本 【不剔除任何】） - bi统计使用
     * @param stageProcessGetExceptDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/getAll", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAll(@RequestBody @Valid StageProcessGetExceptDTO stageProcessGetExceptDTO, BindingResult br) {
        XbbResponse<StageProcessGetExceptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessGetExceptVO stageProcessGetExceptVO = stageProcessService.getAll(stageProcessGetExceptDTO);
                response = new XbbResponse<>(stageProcessGetExceptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 【机会专用】阶段筛选（级联筛选：版本 + 阶段，默认为当前版本 【剔除取消】） - 新增类机会统计使用
     * @param stageProcessGetExceptDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/getExceptCancel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getExceptCancel(@RequestBody @Valid StageProcessGetExceptDTO stageProcessGetExceptDTO, BindingResult br) {
        XbbResponse<StageProcessGetExceptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessGetExceptVO stageProcessGetExceptVO = stageProcessService.getExceptCancel(stageProcessGetExceptDTO);
                response = new XbbResponse<>(stageProcessGetExceptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 【机会专用】阶段筛选（级联筛选：版本 + 阶段，默认为当前版本 【剔除失败、取消】） - 预计类机会统计使用
     * @param stageProcessGetExceptDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/getExceptLoseCancel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getExceptLoseCancel(@RequestBody @Valid StageProcessGetExceptDTO stageProcessGetExceptDTO, BindingResult br) {
        XbbResponse<StageProcessGetExceptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessGetExceptVO stageProcessGetExceptVO = stageProcessService.getExceptLoseCancel(stageProcessGetExceptDTO);
                response = new XbbResponse<>(stageProcessGetExceptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 开启/关闭流程
     * @param stageProcessEnableDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/enable", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String enable(@RequestBody @Valid StageProcessEnableDTO stageProcessEnableDTO, BindingResult br) {
        XbbResponse<StageProcessEnableVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(stageProcessEnableDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(stageProcessEnableDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                StageProcessEnableVO stageProcessEnableVO = stageProcessService.enable(stageProcessEnableDTO);
                response = new XbbResponse<>(stageProcessEnableVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 阶段流程归档
     * @param stageProcessArchiveDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/archive", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String archive(@RequestBody @Valid StageProcessArchiveDTO stageProcessArchiveDTO, BindingResult br) {
        XbbResponse<StageProcessArchiveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessArchiveVO stageProcessArchiveVO = stageProcessService.archive(stageProcessArchiveDTO);
                response = new XbbResponse<>(stageProcessArchiveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 阶段流程取消归档
     * @param stageProcessArchiveDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/cancelArchive", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String cancelArchive(@RequestBody @Valid StageProcessArchiveDTO stageProcessArchiveDTO, BindingResult br) {
        XbbResponse<StageProcessArchiveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessArchiveVO stageProcessArchiveVO = stageProcessService.cancelArchive(stageProcessArchiveDTO);
                response = new XbbResponse<>(stageProcessArchiveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 阶段流程删除
     * @param stageProcessDeleteDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delete(@RequestBody @Valid StageProcessDeleteDTO stageProcessDeleteDTO, BindingResult br) {
        XbbResponse<StageProcessArchiveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessArchiveVO processDeleteVO = stageProcessService.delete(stageProcessDeleteDTO);
                response = new XbbResponse<>(processDeleteVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 流程添加
     * @param stageProcessAddDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/copy", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String copy(@RequestBody @Valid StageProcessAddDTO stageProcessAddDTO, BindingResult br) {
        XbbResponse<StageProcessArchiveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(stageProcessAddDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(stageProcessAddDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                StageProcessArchiveVO processDeleteVO = stageProcessService.copy(stageProcessAddDTO);
                response = new XbbResponse<>(processDeleteVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(@RequestBody @Valid StageProcessAddDTO stageProcessAddDTO, BindingResult br) {
        XbbResponse<StageProcessArchiveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(stageProcessAddDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(stageProcessAddDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                StageProcessArchiveVO processDeleteVO = stageProcessService.add(stageProcessAddDTO);
                response = new XbbResponse<>(processDeleteVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 流程保存
     * @param stageProcessSaveDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String save(@RequestBody @Valid StageProcessSaveDTO stageProcessSaveDTO, BindingResult br) {
        XbbResponse<StageProcessArchiveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(stageProcessSaveDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(stageProcessSaveDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                StageProcessArchiveVO processDeleteVO = stageProcessService.save(stageProcessSaveDTO);
                response = new XbbResponse<>(processDeleteVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 更新阶段比例字段名
     * @param stageRatioAttrNameSetDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/stageRatio/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateStageRatioAttrName(@RequestBody @Valid StageRatioAttrNameSetDTO stageRatioAttrNameSetDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(stageRatioAttrNameSetDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(stageRatioAttrNameSetDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                BaseVO baseVO = stageProcessService.updateStageRatioAttrName(stageRatioAttrNameSetDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 获取阶段比例字段名
     * @param stageRatioAttrNameGetDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/stageRatio/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getStageRatioAttrName(@RequestBody @Valid StageRatioAttrNameGetDTO stageRatioAttrNameGetDTO, BindingResult br) {
        XbbResponse<StageRatioAttrNameGetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageRatioAttrNameGetVO stageRatioAttrNameGetVO = stageProcessService.getStageRatioAttrName(stageRatioAttrNameGetDTO);
                response = new XbbResponse<>(stageRatioAttrNameGetVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 机会数据变更及生成新版本
     * @param opportunityStageAddDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/opportunity/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String opportunityStageAdd(@RequestBody @Valid OpportunityStageAddDTO opportunityStageAddDTO, BindingResult br) {
        XbbResponse<StageProcessArchiveVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(opportunityStageAddDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(opportunityStageAddDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                StageProcessArchiveVO stageProcessArchiveVO = stageProcessService.opportunityStageAdd(opportunityStageAddDTO);
                response = new XbbResponse<>(stageProcessArchiveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 获取当前启用的流程版本
     * @param stageProcessVersionDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/currentEnableVersion", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String currentEnableVersion(@RequestBody @Valid StageProcessVersionDTO stageProcessVersionDTO, BindingResult br) {
        XbbResponse<StageProcessVersionVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                StageProcessVersionVO stageProcessVersionVO = stageProcessService.currentEnableVersion(stageProcessVersionDTO);
                response = new XbbResponse<>(stageProcessVersionVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 批量设置默认值和选项关联
     *
     * @param stageDefaultAndLinkOptionSaveDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/setStageDefaultAndLinkOption", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String setStageDefaultAndLinkOption(@RequestBody @Valid StageDefaultAndLinkOptionSaveDTO stageDefaultAndLinkOptionSaveDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                BaseVO baseVO = stageProcessService.setStageDefaultAndLinkOption(stageDefaultAndLinkOptionSaveDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 排序
     *
     * @param stageProcessSortDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/sort", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String sort(@RequestBody @Valid StageProcessSortDTO stageProcessSortDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                BaseVO baseVO = stageProcessService.sort(stageProcessSortDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
